<template>
  <view class="ad-reward-container">
    <!-- 广告奖励卡片 -->
    <view class="ad-card" @click="handleWatchAd">
      <view class="ad-header">
        <image class="ad-icon" src="/static/icons/video-play.png" mode="aspectFit"></image>
        <view class="ad-title">观看广告获得积分</view>
      </view>
      
      <view class="ad-content">
        <view class="reward-info">
          <text class="reward-text">完整观看广告可获得</text>
          <text class="reward-points">{{ rewardPoints }}</text>
          <text class="reward-unit">积分</text>
        </view>
        
        <view class="ad-stats">
          <text class="stats-text">今日已观看: {{ todayCount }}/{{ dailyLimit }}</text>
        </view>
      </view>
      
      <view class="ad-footer">
        <button 
          class="watch-btn" 
          :class="{ 'disabled': !canWatch || isLoading }"
          :disabled="!canWatch || isLoading"
          @click.stop="handleWatchAd"
        >
          <text v-if="isLoading">加载中...</text>
          <text v-else-if="!canWatch">今日已达上限</text>
          <text v-else>立即观看</text>
        </button>
      </view>
    </view>
    
    <!-- 广告说明 -->
    <view class="ad-tips">
      <view class="tip-item">
        <text class="tip-icon">•</text>
        <text class="tip-text">需要完整观看广告才能获得积分奖励</text>
      </view>
      <view class="tip-item">
        <text class="tip-icon">•</text>
        <text class="tip-text">每日最多可观看{{ dailyLimit }}次广告</text>
      </view>
      <view class="tip-item">
        <text class="tip-icon">•</text>
        <text class="tip-text">积分将在观看完成后立即到账</text>
      </view>
    </view>
    
    <!-- 加载提示 -->
    <uni-popup ref="loadingPopup" type="center" :mask-click="false">
      <view class="loading-popup">
        <uni-load-more status="loading" :content-text="loadingText"></uni-load-more>
      </view>
    </uni-popup>
    
    <!-- 结果提示 -->
    <uni-popup ref="resultPopup" type="center">
      <view class="result-popup">
        <view class="result-icon">
          <image v-if="adResult.success" src="/static/icons/success.png" mode="aspectFit"></image>
          <image v-else src="/static/icons/error.png" mode="aspectFit"></image>
        </view>
        <view class="result-title">{{ adResult.title }}</view>
        <view class="result-message">{{ adResult.message }}</view>
        <button class="result-btn" @click="closeResultPopup">确定</button>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  name: 'AdReward',
  data() {
    return {
      rewardPoints: 1, // 奖励积分
      todayCount: 0,   // 今日观看次数
      dailyLimit: 50,  // 每日限制次数
      canWatch: true,  // 是否可以观看
      isLoading: false, // 是否加载中
      loadingText: {
        contentdown: '准备广告中...',
        contentrefresh: '加载广告中...',
        contentnomore: '加载完成'
      },
      adResult: {
        success: false,
        title: '',
        message: ''
      },
      rewardedVideoAd: null
    }
  },
  
  mounted() {
    this.loadAdLimit()
    this.initAd()
  },
  
  methods: {
    /**
     * 初始化广告
     */
    initAd() {
      // #ifdef MP-WEIXIN
      if (wx.createRewardedVideoAd) {
        this.rewardedVideoAd = wx.createRewardedVideoAd({
          adUnitId: 'adunit-rewardedvideo'
        })
        
        this.rewardedVideoAd.onLoad(() => {
          console.log('激励视频广告加载成功')
        })
        
        this.rewardedVideoAd.onError((err) => {
          console.error('激励视频广告加载失败:', err)
        })
        
        this.rewardedVideoAd.onClose((res) => {
          this.handleAdClose(res)
        })
      }
      // #endif
    },
    
    /**
     * 加载广告限制信息
     */
    async loadAdLimit() {
      try {
        // 模拟获取广告限制信息
        const token = uni.getStorageSync('token')
        if (token) {
          const res = await uni.request({
            url: 'http://localhost:3000/api/ads/limit',
            method: 'GET',
            header: { 'Authorization': `Bearer ${token}` }
          })
          
          if (res.data && res.data.success) {
            const limitInfo = res.data.data
            this.todayCount = limitInfo.todayCount || 0
            this.dailyLimit = limitInfo.dailyLimit || 50
            this.canWatch = limitInfo.canWatch !== false
            this.rewardPoints = limitInfo.rewardPoints || 1
          }
        } else {
          // 未登录时的默认值
          this.todayCount = 0
          this.dailyLimit = 50
          this.canWatch = true
          this.rewardPoints = 1
        }
      } catch (error) {
        console.error('加载广告限制失败:', error)
        // 使用默认值
        this.todayCount = 0
        this.dailyLimit = 50
        this.canWatch = true
        this.rewardPoints = 1
      }
    },
    
    /**
     * 处理观看广告
     */
    async handleWatchAd() {
      if (!this.canWatch || this.isLoading) {
        return
      }
      
      if (this.todayCount >= this.dailyLimit) {
        uni.showToast({
          title: '今日观看次数已达上限',
          icon: 'none'
        })
        return
      }
      
      this.isLoading = true
      
      try {
        // #ifdef MP-WEIXIN
        if (this.rewardedVideoAd) {
          await this.rewardedVideoAd.show()
        } else {
          throw new Error('广告未初始化')
        }
        // #endif
        
        // #ifndef MP-WEIXIN
        // 非微信环境模拟广告观看
        setTimeout(() => {
          this.handleAdClose({ isEnded: true })
        }, 2000)
        // #endif
        
      } catch (error) {
        this.isLoading = false
        console.error('观看广告失败:', error)
        
        this.adResult = {
          success: false,
          title: '广告播放失败',
          message: error.message || '请检查网络连接后重试'
        }
        
        this.$refs.resultPopup.open()
      }
    },
    
    /**
     * 处理广告关闭
     */
    async handleAdClose(res) {
      this.isLoading = false
      
      try {
        if (res && res.isEnded) {
          // 观看完成，记录奖励
          const token = uni.getStorageSync('token')
          if (token) {
            const rewardRes = await uni.request({
              url: 'http://localhost:3000/api/ads/reward',
              method: 'POST',
              header: { 'Authorization': `Bearer ${token}` },
              data: {
                adType: 'rewardedVideo',
                platform: 'miniprogram',
                timestamp: Date.now()
              }
            })
            
            if (rewardRes.data && rewardRes.data.success) {
              const reward = rewardRes.data.data
              this.adResult = {
                success: true,
                title: '恭喜获得奖励！',
                message: `您获得了 ${reward.points || this.rewardPoints} 积分`
              }
              
              // 更新观看次数
              this.todayCount++
              this.canWatch = this.todayCount < this.dailyLimit
              
              // 触发积分更新事件
              this.$emit('reward-earned', reward)
              
              // 通知父组件刷新积分
              uni.$emit('points-updated')
            }
          } else {
            // 未登录时的模拟奖励
            this.adResult = {
              success: true,
              title: '恭喜获得奖励！',
              message: `您获得了 ${this.rewardPoints} 积分`
            }
            
            this.todayCount++
            this.canWatch = this.todayCount < this.dailyLimit
          }
        } else {
          // 未完整观看
          this.adResult = {
            success: false,
            title: '未获得奖励',
            message: '需要完整观看广告才能获得积分'
          }
        }
        
        this.$refs.resultPopup.open()
        
      } catch (error) {
        console.error('处理广告奖励失败:', error)
        
        this.adResult = {
          success: false,
          title: '奖励发放失败',
          message: '请稍后重试'
        }
        
        this.$refs.resultPopup.open()
      }
    },
    
    /**
     * 关闭结果弹窗
     */
    closeResultPopup() {
      this.$refs.resultPopup.close()
    }
  }
}
</script>

<style lang="scss" scoped>
.ad-reward-container {
  padding: 20rpx;
}

.ad-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 8rpx 32rpx rgba(102, 126, 234, 0.3);
  color: white;
}

.ad-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.ad-icon {
  width: 48rpx;
  height: 48rpx;
  margin-right: 16rpx;
}

.ad-title {
  font-size: 32rpx;
  font-weight: bold;
}

.ad-content {
  margin-bottom: 30rpx;
}

.reward-info {
  display: flex;
  align-items: baseline;
  margin-bottom: 16rpx;
}

.reward-text {
  font-size: 28rpx;
  opacity: 0.9;
}

.reward-points {
  font-size: 48rpx;
  font-weight: bold;
  color: #FFD700;
  margin: 0 8rpx;
}

.reward-unit {
  font-size: 28rpx;
  opacity: 0.9;
}

.ad-stats {
  opacity: 0.8;
}

.stats-text {
  font-size: 24rpx;
}

.ad-footer {
  display: flex;
  justify-content: center;
}

.watch-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 2rpx solid rgba(255, 255, 255, 0.3);
  border-radius: 50rpx;
  padding: 20rpx 60rpx;
  color: white;
  font-size: 28rpx;
  font-weight: bold;
  backdrop-filter: blur(10rpx);
  transition: all 0.3s ease;
  
  &:not(.disabled):active {
    background: rgba(255, 255, 255, 0.3);
    transform: scale(0.95);
  }
  
  &.disabled {
    opacity: 0.5;
    background: rgba(255, 255, 255, 0.1);
  }
}

.ad-tips {
  background: #f8f9fa;
  border-radius: 16rpx;
  padding: 24rpx;
}

.tip-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.tip-icon {
  color: #667eea;
  font-weight: bold;
  margin-right: 12rpx;
  line-height: 1.5;
}

.tip-text {
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
  flex: 1;
}

.loading-popup {
  background: white;
  border-radius: 16rpx;
  padding: 40rpx;
  min-width: 300rpx;
  text-align: center;
}

.result-popup {
  background: white;
  border-radius: 20rpx;
  padding: 40rpx;
  min-width: 400rpx;
  text-align: center;
}

.result-icon {
  margin-bottom: 20rpx;
  
  image {
    width: 80rpx;
    height: 80rpx;
  }
}

.result-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
}

.result-message {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 30rpx;
  line-height: 1.5;
}

.result-btn {
  background: #667eea;
  color: white;
  border-radius: 50rpx;
  padding: 20rpx 60rpx;
  font-size: 28rpx;
  border: none;
  
  &:active {
    background: #5a6fd8;
  }
}
</style>